package com.example.group.network.express_plus_app.data;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.example.group.network.express_plus_app.R;
import com.example.group.network.express_plus_app.bean.MyResponse;

import com.example.group.network.express_plus_app.http.GsonRequest;
import com.example.group.network.express_plus_app.http.MySingleton;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册数据层
 * @author 夏宁
 * @email 1941512303@qq.com
 * @date 2021/3/27 13:46
 */
public class RegisterDataSource {
    RequestQueue queue;
    String server_ip ;
    String register_url;
    public void register(String userPhone, String userPassword, Context applicationContext){
        server_ip =applicationContext.getString(R.string.server_ip);
        register_url=server_ip+"express-user/user-open/common-user-register?";
        //初始化queue
        queue= MySingleton.getInstance(applicationContext).
                getRequestQueue();
        GsonRequest<MyResponse> tokenGsonRequest=new GsonRequest<MyResponse>(register_url, Request.Method.POST, MyResponse.class, null, new com.android.volley.Response.Listener<MyResponse>() {
            @Override
            public void onResponse(MyResponse response) {
                Log.i("注册结果", response.getOk().toString());
                //注册结果回调
                registerResponseListener.setRegisterResponse(response);
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MyResponse myResponse = new MyResponse(500,false);
                registerResponseListener.setRegisterResponse(myResponse);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> parms=new HashMap<>();
                parms.put("userPhone",userPhone);
                parms.put("userPassword",userPassword);
                return parms;
            }
        };
        tokenGsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(tokenGsonRequest);
    }

    //回调使用
    private RegisterResponseListener registerResponseListener; //定义一个用户信息监听器
    public void setRegisterResponseListener(RegisterResponseListener listener){
        registerResponseListener=listener;
    }
    public interface RegisterResponseListener{
        void setRegisterResponse(MyResponse myResponse);
    }
}
